
#include <csignal>
#include <iostream>
#include <memory>
#include <thread>
#include <yaml-cpp/yaml.h>

#include "lighter.h"
#include "binance.h"
#include "market_persistor.h"

boost::asio::io_context ioc;
MarketPersistor* marketPersistor = nullptr;


void signalHandler(int signum) {
    std::cout << "\n捕获到信号 " << signum << "，正在安全退出..." << std::endl;
    ioc.stop();
}

int main() {
    try {
        // 注册 Ctrl+C 信号
        std::signal(SIGINT, signalHandler);
        std::signal(SIGTERM, signalHandler);

        // 初始化共享内存 MARKETStruct
        SharedMemory<MARKETStruct> marketShm("_v1");
        MARKETStruct* marketShmPtr = marketShm.get_ptr();

        // 读取配置文件路径
        std::string config_path = "../config/config.yaml";
        YAML::Node config = YAML::LoadFile(config_path);

        // 创建 io_context 工作守卫
        auto work = boost::asio::make_work_guard(ioc);

        // 初始化 SSL 上下文
        boost::asio::ssl::context ssl_ctx{boost::asio::ssl::context::tlsv12_client};
        ssl_ctx.set_default_verify_paths();
        ssl_ctx.set_verify_mode(boost::asio::ssl::verify_peer);

        // ----------- 动态实例化客户端 -----------
        std::shared_ptr<LighterClient> lighterClient;
        std::shared_ptr<BinanceClient> binanceClient;

        if (config["lighter"]) {
            std::cout << "✅ 检测到 lighter 配置，创建 LighterClient..." << std::endl;
            lighterClient = std::make_shared<LighterClient>(config_path, marketShmPtr, ioc, ssl_ctx);
        }

        if (config["binance"]) {
            std::cout << "✅ 检测到 binance 配置，创建 BinanceClient..." << std::endl;
            binanceClient = std::make_shared<BinanceClient>(config_path, marketShmPtr, ioc, ssl_ctx);
        }

        if (!lighterClient && !binanceClient) {
            std::cerr << "❌ 错误：配置文件中未找到 lighter 或 binance 配置。" << std::endl;
            return EXIT_FAILURE;
        }

        // ----------- 启动客户端 -----------
        if (lighterClient) {
            lighterClient->run();
        }
        if (binanceClient) {
            binanceClient->run();
        }

        // 启动 io_context 事件循环
        ioc.run();

        std::cout << "✅ 程序正常退出。" << std::endl;

    } catch (const std::exception& e) {
        std::cerr << "❌ 程序异常: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
